package com.hm.manage.utils;

import com.hm.manage.dto.DiskUsage;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class DiskSpaceChecker {

//    public static void main(String[] args) {
//        String host = "50.58.191.86";
//        String user = "root";
//        String password = "WUjin320@2019";
//        int port = 2343;
//
//        List<DiskUsage> diskUsages = getDiskUsage(host, port, user, password);
//        diskUsages.forEach(System.out::println);
//    }

    public List<DiskUsage> getDiskUsage(String host, int port, String user, String password) {
        List<DiskUsage> result = new ArrayList<>();

        JSch jsch = new JSch();
        Session session = null;
        ChannelExec channel = null;

        try {
            // 建立SSH连接
            session = jsch.getSession(user, host, port);
            session.setPassword(password);
            // 修改代码增加配置
            session.setConfig("PreferredAuthentications", "password"); // 强制使用密码认证
            jsch.setLogger(new Logger() { // 启用详细日志
                public void log(int level, String message) {
                    System.out.println("JSCH LOG: " + message);
                }
                public boolean isEnabled(int level) { return true; }
            });

            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            // 执行命令
            channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand("df -h");
            InputStream in = channel.getInputStream();
            InputStream err = channel.getErrStream();
            channel.connect();

            // 读取命令输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line;
            boolean isHeaderSkipped = false;
            while ((line = reader.readLine()) != null) {
                if (!isHeaderSkipped) {
                    isHeaderSkipped = true;
                    continue; // 跳过标题行
                }
                DiskUsage usage = parseLine(line);
                if (usage != null) {
                    result.add(usage);
                }
            }

            // 检查错误
            BufferedReader errReader = new BufferedReader(new InputStreamReader(err));
            StringBuilder errorMsg = new StringBuilder();
            while (errReader.ready()) {
                errorMsg.append(errReader.readLine()).append("\n");
            }
            if (!errorMsg.toString().isEmpty()) {
                throw new RuntimeException("Command error: " + errorMsg);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channel != null) channel.disconnect();
            if (session != null) session.disconnect();
        }

        return result;
    }

    private static DiskUsage parseLine(String line) {
        // 使用正则表达式分割多个空格
        String[] parts = line.split("\\s+");
        if (parts.length < 6) return null;

        return new DiskUsage(
                parts[0],        // 文件系统
                parts[1],        // 总大小
                parts[2],        // 已用
                parts[3],        // 可用
                parts[4],        // 使用百分比
                parts[5]         // 挂载点
        );
    }

    public String checkGAHbpDisk(){
        String con = "磁盘占用情况正常";
        // 大数据服务器清单：50.58.191.82，50.58.191.83，50.58.191.84，50.58.191.85，50.58.191.86，50.58.191.87
        String singleHbpDisk82 = getSingleHbpDisk("50.58.191.82");
        String singleHbpDisk83 = getSingleHbpDisk("50.58.191.83");
        String singleHbpDisk84 = getSingleHbpDisk("50.58.191.84");
        String singleHbpDisk85 = getSingleHbpDisk("50.58.191.85");
        String singleHbpDisk86 = getSingleHbpDisk("50.58.191.86");
        String singleHbpDisk87 = getSingleHbpDisk("50.58.191.87");
        con = singleHbpDisk82+singleHbpDisk83+singleHbpDisk84+singleHbpDisk85+singleHbpDisk86+singleHbpDisk87;

        return con;
    }

    private String getSingleHbpDisk(String host) {
        List<DiskUsage> diskUsage82 = getDiskUsage(host, 2343, "root", "WUjin320@2019");
        String con82 = host+":";
        for (DiskUsage diskUsage : diskUsage82) {
            //log.info("---------------------------------");
            //log.info("diskUsage.getUsePercent()"+diskUsage.getUsePercent());
            Double value = Double.valueOf(diskUsage.getUsePercent().replace("%",""));
            if (value > 80.0) {
                con82 = con82 +"异常"+ diskUsage.getMountedOn() +"占用" +diskUsage.getUsePercent()+";";
            }
        }
        if (con82.equals(host+":")) {
            con82 = host+":正常<br>";
        } else {
            con82 = con82+"<br>";
        }
        return con82;
    }


}
